<?php

namespace App\Store\Controllers\Financial\Goods;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Financial\Goods\GoodsWarning;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Basic\GoodsStyle;
use App\Store\Validate\Financial\Goods\GoodsWarning as ValidateFinancialGoodsGoodsWarning;
use App\Common\Services\CommonExcelExport;
use App\Store\Models\Goods\GoodsReplenishInfolist;
use App\Store\Models\Goods\GoodsStockList;
use Maatwebsite\Excel\Facades\Excel;
/**
 * 库存预警信息
 */
class GoodsWarningController extends Controller
{
    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        $list = GoodsWarning::getList($request);

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 获取详情
     */
    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = GoodsWarning::with(['storeinfo','goodscategoryinfo','goodsstyleinfo'])->where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $info=$info->toArray();
        $info['warningdays']=$info['warning_at']>0?ceil((time()-$info['warning_at'])/86400):0;
        //预警后补货件数
        if($info['warningdays']>0){
            $info['replenish_num']=GoodsReplenishInfolist::where(['audit_status'=>2,'cp_id'=>$cp_id,'store_id'=>$info['store_id'],'goods_category_id'=>$info['goods_category_id'],'goods_style_id'=>$info['goods_style_id']])
            ->where([['create_at','>=',$info['warning_at']]])->sum('count');
        }else{
            $info['replenish_num']=0;
        }
        //当前库存
        $info['stock_num']=GoodsStockList::where(['cp_id'=>$cp_id,'store_id'=>$info['store_id'],'goods_category_id'=>$info['goods_category_id'],'goods_style_id'=>$info['goods_style_id']])
            ->sum('count');

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 新增
     */
    public function dopostadd(Request $request)
    {

        $req_data = $request->only(['store_id','goods_category_id','goods_style_id','safety_stock_min','safety_stock_max','warning_stock','remark']);

        $Validate = new ValidateFinancialGoodsGoodsWarning();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $accountinfo= StoreCommon::getCurrentAccountinfo($request);

        $storeinfo = SiteStore::where(['id' => $req_data['store_id'], 'cp_id' => $accountinfo['cp_id']])->first();
        if (!$storeinfo) {
            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }
        $categoryinfo = GoodsCategory::where(['id' => $req_data['goods_category_id'],'store_id' => $req_data['store_id'], 'cp_id' => $accountinfo['cp_id']])->first();
        if (!$categoryinfo) {
            return response()->json(['code' => '001', 'msg' => '无效类别参数']);
        }
        $styleinfo = GoodsStyle::where(['id' => $req_data['goods_style_id'], 'cp_id' => $accountinfo['cp_id']])->first();
        if (!$styleinfo) {
            return response()->json(['code' => '001', 'msg' => '无效款式参数']);
        }
        if ($req_data['safety_stock_min'] > $req_data['safety_stock_max']) {
            return response()->json(['code' => '001', 'msg' => '安全库存最小值不能大于最大值']);
        }

        $data = $req_data;
        $data['create_account_id'] = $accountinfo['id'];
        $data['update_account_id'] = $accountinfo['id'];
        $data['create_account_real_name'] = $accountinfo['real_name'];
        $data['update_account_real_name'] = $accountinfo['real_name'];
        $data['cp_id'] = $accountinfo['cp_id'];
        $data['create_at'] = time();
        $data['update_at'] = time();
        GoodsWarning::create($data);
        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     * 编辑
     */
    public function dopostedit(Request $request)
    {
        $req_data = $request->only(['id','goods_category_id','goods_style_id','safety_stock_min','safety_stock_max','warning_stock','remark']);

        
        $Validate = new ValidateFinancialGoodsGoodsWarning('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $accountinfo= StoreCommon::getCurrentAccountinfo($request);
        
        $info = GoodsWarning::where([['id', $req_data['id']], ['cp_id', $accountinfo['cp_id']], ['is_del', 1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        
        $categoryinfo = GoodsCategory::where(['id' => $req_data['goods_category_id'],'store_id' => $info->store_id, 'cp_id' => $accountinfo['cp_id']])->first();
        if (!$categoryinfo) {
            return response()->json(['code' => '001', 'msg' => '无效类别参数']);
        }

        $styleinfo = GoodsStyle::where(['id' => $req_data['goods_style_id'], 'cp_id' => $accountinfo['cp_id']])->first();
        if (!$styleinfo) {
            return response()->json(['code' => '001', 'msg' => '无效款式参数']);
        }
        if ($req_data['safety_stock_min'] > $req_data['safety_stock_max']) {
            return response()->json(['code' => '001', 'msg' => '安全库存最小值不能大于最大值']);
        }
        $data = $req_data;
        unset($data['id']);
        $data['update_at'] = time();
        $data['update_account_id'] = $accountinfo['id'];
        $data['update_account_real_name'] = $accountinfo['real_name'];
        GoodsWarning::where(['id' => $req_data['id']])->update($data);
        return response()->json(['code' => '000', 'msg' => '编辑成功']);
    }
    /**
     * 删除
     */
    public function dodel(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = GoodsWarning::where([['id', $id], ['cp_id', $cp_id], ['is_del', 1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        GoodsWarning::where([['id', $id]])->update(['is_del' => 2, 'del_at' => time()]);

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        $list = GoodsWarning::getList($request)['list'];
        $exceldata = [];
        $storeNames = array_unique(array_map(function($item) {
            return $item['storeinfo']['store_name'];
        }, $list));
        $row = [
            ['store_name'=>'库龄分析报表'],
            ['store_name'=>'所属门店：'.join(',' ,$storeNames)],
            [
                'store_name' => '所属门店',
                'is_gram' => '在售方式',
                'goods_category_name' => '商品类别',
                'goods_style_name' => '款式',
                'stock_num' => '当前库存',
                'safety_stock' => '安全库存',
                'warning_stock' => '异常库存',
                'warningdays' => '异常天数',
                'replenish_num' => '补货件数',
            ]
        ];
        foreach ($list as $val) {
            $exceldata[] = [
                'store_name' => $val['storeinfo']['store_name'],
                'is_gram' => $val['goodscategoryinfo']['is_gram']==1?'按克':'按件',
                'goods_category_name' => $val['goodscategoryinfo']['category_name'],
                'goods_style_name' => $val['goodsstyleinfo']?$val['goodsstyleinfo']['style_name']:'',
                'stock_num'=>$val['stock_num'],
                'safety_stock' => $val['safety_stock_min'].'~'.$val['safety_stock_max'],
                'warning_stock' => $val['warning_stock'],
                'warningdays' => $val['warningdays'],
                'replenish_num' => $val['replenish_num'],
            ];
        }

        $filename = '库存预警信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }



}
